/*
 * ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Topless JSF.
 *
 * The Initial Developer of the Original Code is
 * Marco Antonio Villalobos, Jr. (mvillalobos@kineteque.com).
 * Portions created by the Initial Developer are Copyright (C) 2010
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Marco Antonio Villalobos, Jr. (mvillalobos@kineteque.com).
 *
 * ***** END LICENSE BLOCK *****
 */

package kineteque.jsf.topless.managedbeans;

import kineteque.jsf.topless.components.table.UITable;
import org.apache.log4j.Logger;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.AjaxBehaviorEvent;
import javax.sql.DataSource;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Map;

/**
 * Provides a managed bean for the complex request example.
 */
@ManagedBean(name = "complexRequest")
@RequestScoped
public class ComplexRequest implements Serializable {

    /** The logger for this class. */
    private final static Logger logger = Logger.getLogger(ComplexRequest.class);

    /** The topless table that this managed bean interacts with. */
    private UITable toplessTable;

    /**
     * Retrieves the topless table.
     *
     * @return The topless table.
     */
    public UITable getToplessTable() {
        return toplessTable;
    }

    /**
     * Assigns the topless table.
     *
     * @param toplessTable The topless table.
     */
    public void setToplessTable(UITable toplessTable) {
        this.toplessTable = toplessTable;
    }

    /**
     * Provides an action event for removing a row from the table.
     *
     * @param e The action event.
     * @throws SQLException When there is an sql error.
     */
    public void remove(ActionEvent e) throws SQLException {

        FacesContext ctx = FacesContext.getCurrentInstance();        
        Map<String,Object> row = (Map<String,Object>) toplessTable.getTable().getRowData();
        Integer id = (Integer)row.get("WIDGET_ID");
        if (logger.isDebugEnabled()) {
            logger.debug(new StringBuilder().append("Attempt to remove widget with widget_id = ").append(id).append(" in phase = ").append(FacesContext.getCurrentInstance().getCurrentPhaseId()).append(".").toString());
        }
        ApplicationConfig cfg = (ApplicationConfig)ctx.getExternalContext(). getApplicationMap().get("appConfig");
        DataSource ds = cfg.getDataSource();
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = ds.getConnection();
            pstmt = con.prepareStatement("DELETE FROM widgets WHERE widget_id = ?");
            pstmt.setInt(1,id);
            pstmt.executeUpdate();
            toplessTable.remove(row);
        } finally {
            if (pstmt!=null) {
                pstmt.close();
            }
            if (con!=null) {
                con.close();
            }
        }
    }
}
